package com.mach.platform.service;

import com.mach.platform.domain.CustomizeUserInfo;
import com.mach.platform.utils.Utils;
import com.mach.platform.utils.security.SecurityUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;


@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        String name = request.getPrincipal().getName();
        List<String> cookies = request.getHeaders().get("Cookie");
        CustomizeUserInfo ifLogin = SecurityUtils.getCurrentUser();
        if (ifLogin != null) {
            String cookie = cookies.get(0);
            System.out.println("dddd: "+ cookie);
            map.put("cookie", cookie.replace("JSESSIONID", Utils.StrToHexString(name)));
        }
        System.out.println(ifLogin == null);
        System.out.println("beforeHandshake:Cookie:" + cookies.get(0));
        System.out.println("beforeHandshake:" + ifLogin.getName());
        System.out.println("name:" + name);
        return ifLogin != null;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
